/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable @typescript-eslint/no-unused-expressions */
import React, { useMemo, useState } from 'react';
import { Modal, Form, message } from 'antd';
import { patternCheck } from '@/utils/patterns';
import { cashBackAdd, cashBackCheck, cashBackDispatch } from '@/services/operatorManagement';
import AddContent from './AddContent';
import ExportContent from './ExportContent';
import DispatchContent from './DispatchContent';
import { download } from './utils';

interface PageProps {
  open: boolean;
  type: string;
  onClose: () => void;
  refresh?: () => void;
}

interface MoneyStatus {
  total_amount: number;
  status: number;
}

const OperateModal: React.FC<PageProps> = (props) => {
  const { open, onClose, refresh, type } = props;
  const [form] = Form.useForm();

  const [confirmLoading, setConfirmLoading] = useState(false);

  const [status, setStatus] = useState<MoneyStatus>({
    total_amount: 0,
    status: 0,
  });

  const [rewardAmount, setRewardAmount] = useState('');

  const title = useMemo(() => {
    switch (type) {
      case 'add':
        return '新增活动驿站';
      case 'export':
        return '导出';
      case 'dispatch':
        return '批量发放';
      default:
        return '';
    }
  }, [type]);

  const okText = useMemo(() => {
    switch (type) {
      case 'add':
        return '保存';
      case 'export':
        return '导出';
      case 'dispatch':
        return '确认发放';
      default:
        return '';
    }
  }, [type]);

  const handleClose = () => {
    form.resetFields();
    setStatus({} as MoneyStatus);
    onClose && onClose();
  };

  const onOk = () => {
    form.validateFields().then((res) => {
      setConfirmLoading(true);
      switch (type) {
        case 'add':
          cashBackAdd(res).then((result) => {
            setConfirmLoading(false);
            if (result.code == 0) {
              message.success('新增成功！');
              handleClose();
              refresh && refresh();
            } else {
              message.error(result.msg);
            }
          });
          break;
        case 'export':
          download(res)
            .then((url) => {
              window.open(url);
              setConfirmLoading(false);
              handleClose();
            })
            .catch((msg) => {
              if (msg) {
                message.error(msg);
              }
            });
          break;
        case 'dispatch':
          cashBackDispatch({ batch: res.batch }).then((result) => {
            setConfirmLoading(false);
            if (result.code == 0) {
              message.success('发放成功！');
              handleClose();
              refresh && refresh();
            } else {
              message.error(result.msg);
            }
          });
          break;
        default:
          break;
      }
    });
  };

  const onCheckStatus = async (mobile: string) => {
    const { code: checkCode } = patternCheck({ mobile });
    if (!mobile) {
      setStatus({} as MoneyStatus);
      return;
    }
    if (checkCode > 0) return;

    try {
      const { code, data, msg } = await cashBackCheck({ phone: mobile });
      if (code == 0) {
        setStatus(data as MoneyStatus);
      } else {
        message.error(msg);
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Modal
      width={450}
      destroyOnClose
      centered
      okText={okText}
      title={title}
      visible={open}
      onOk={onOk}
      onCancel={handleClose}
      confirmLoading={confirmLoading}
      okButtonProps={{
        disabled:
          (type === 'add' && status.status == 1) ||
          (type === 'dispatch' && (rewardAmount as unknown as number) == 0),
      }}
    >
      {type == 'add' && <AddContent status={status} checkStatus={onCheckStatus} form={form} />}
      {type == 'export' && <ExportContent form={form} />}
      {type == 'dispatch' && (
        <DispatchContent
          form={form}
          setRewardAmount={(reward_amount) => setRewardAmount(reward_amount)}
        />
      )}
    </Modal>
  );
};

export default OperateModal;
